package cn.shopifymall.springbucks.controller;

import cn.shopifymall.springbucks.entity.Coffee;
import cn.shopifymall.springbucks.service.CoffeeService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author efair
 * @since 2022-08-05
 */
@Slf4j
@RestController
@RequestMapping("/coffee")
public class CoffeeController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CoffeeService coffeeService;

    @GetMapping("/count")
    public long count() {
        long count = coffeeService.count();
        return count;
    }

    @GetMapping("/getPageCoffeeList/{pageIndex}-{pageSize}")
    public Page<Coffee> getPageCoffeeList(@PathVariable("pageIndex") Integer pageIndex,
                                          @PathVariable("pageSize") Integer pageSize) {
        Page<Coffee> page = new Page<>(pageIndex, pageSize);
        return coffeeService.getPageCoffeeList(page);
    }

    @PostMapping("/getCoffeeByIds")
    public List<Coffee> getCoffeeByIds(@RequestBody List<String> ids) {
        // 从redis缓存中提取数据
        String jsonString = (String) stringRedisTemplate.opsForValue().get("coffee:ids:" + ids.toString());

        if (StringUtils.isEmpty(jsonString)) {
            log.info("返回从数据库中获得的数据");
            List<Coffee> list = coffeeService.getCoffeeByIds(ids);
            stringRedisTemplate.opsForValue().set("coffee:ids:" + ids, JSON.toJSONString(list));
            return list;
        } else {
            log.info("返回从redis缓存中获得的数据");
            List<Coffee> list = JSON.parseObject(jsonString, new TypeReference<List<Coffee>>() {});
            return list;
        }
    }

    @DeleteMapping("/deleteByCoffeeId/{id}")
    public boolean deleteByCoffeeId(@PathVariable String id) {
        return coffeeService.removeById(id);
    }

    @PutMapping("/updateCoffee")
    public Coffee updateCoffee(@RequestBody Coffee coffee) {
        boolean flag = coffeeService.saveOrUpdate(coffee);
        return flag ? coffee : null;
    }

}
